package com.zhangxin.aiInterview.manager.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * disruptor生产者
 */
@Component
public class WsEventProducer {
    /**
     * disruptor
     */
    @Resource
    private Disruptor<WsEvent> chatWordsEventDisruptor;

    /**
     * 生产消息
     * @param userId 用户id
     * @param userAnswer 用户回答
     * @param aiQuestion ai问题文本
     * @param isTts 是否开启文本转语音
     * @param gender 性别
     * @param interviewType 面试模式
     */
    public void publishEvent(Long userId, String userAnswer,String aiQuestion, Boolean isTts,String gender,Integer interviewType) {
        //获取环形缓冲区(队列)
        RingBuffer<WsEvent> ringBuffer = chatWordsEventDisruptor.getRingBuffer();
        //获取可以存放任务的位置
        //如果当前位置的消息还没有被处理，则会阻塞等待
        long next = ringBuffer.next();
        //获取这个空事件
        WsEvent wsEvent = ringBuffer.get(next);
        wsEvent.setUserId(userId);
        wsEvent.setUserContent(userAnswer);
        wsEvent.setTxt(aiQuestion);
        wsEvent.setTTs(isTts);
        wsEvent.setGender(gender);
        wsEvent.setInterviewType(interviewType);
        //发布事件
        ringBuffer.publish(next);
    }

    /**
     * 生产消息(ai模拟面试)
     * @param userId 用户id
     * @param userAnswer 用户回答
     * @param gender 性别
     * @param interviewType 面试类型（技术面 or hr面）
     */
    public void publishEvent(Long userId, String userAnswer,String gender,Integer interviewType) {
        publishEvent(userId, userAnswer, "", false, gender, interviewType);
    }

    /**
     * 生产消息 (AI面试官问题转语音)
     * @param userId 用户id
     * @param aiQuestion ai问题文本
     * @param gender 性别
     */
    public void publishEvent(Long userId, String aiQuestion, String gender) {
        publishEvent(userId, "", aiQuestion, true, gender, -1);
    }


    /**
     * 优雅停机
     * 等待disruptor队列中所有任务处理完才会关闭
     */
    @PreDestroy
    public void close() {
        chatWordsEventDisruptor.shutdown();
    }
}
